package product

import (
	"fmt"
	"net/http"
	"strconv"

	"gitee.com/zoneaurora/shop/internal/common"
	"gitee.com/zoneaurora/shop/internal/dto"
	"gitee.com/zoneaurora/shop/internal/model"
	"github.com/gin-gonic/gin"
)

func GetProductByID(c *gin.Context) {
	db := common.DB()
  // 获取请求参数
  id := c.Param("id")

  var product model.Product
  if err := db.First(&product, id).Error; err != nil {
		common.JSON(c, http.StatusInternalServerError, "产品数据获取失败", nil)
    return
  }
  common.JSON(c, http.StatusOK, "产品数据获取成功", product)
}

func GetProducts(c *gin.Context) {
	db := common.DB()

  // 获取请求参数
  page := c.DefaultQuery("page", "1")
  pageSize := c.DefaultQuery("pageSize", "12")
  keywords := fmt.Sprintf("%%%s%%", c.DefaultQuery("keywords", ""))
  categoryID := fmt.Sprintf("%%%s%%", c.DefaultQuery("category", ""))
  iPage, err := strconv.Atoi(page)
  if err != nil {
		common.JSON(c, http.StatusBadRequest, "请求出错", nil)
    return
  }
  iPageSize, err := strconv.Atoi(pageSize)
  if err != nil {
		common.JSON(c, http.StatusBadRequest, "请求出错", nil)
    return
  }

  // 查询对应数据
  var products []model.Product
  var total int64
  // 记录总数
  res := db.Where("name LIKE ? AND category_id LIKE ?", keywords, categoryID).Find(&products)
  if  res.Error != nil {
		common.JSON(c, http.StatusInternalServerError, "产品数据获取失败", nil)
		return
  }
  total = res.RowsAffected
  // 查询内容
	if err := db.Where("name LIKE ? AND category_id LIKE ?", keywords, categoryID).Offset((iPage-1) * iPageSize).
      Limit(iPageSize).Order("created_at desc").Find(&products).Error; err != nil {
		common.JSON(c, http.StatusInternalServerError, "产品数据获取失败", nil)
		return
	}

  // 封装去除不必要数据
  var respProducts []dto.ProductDto
  for _, v := range products {
    respProducts = append(respProducts, dto.ToProductDto(v))
  }

  common.JSON(c, http.StatusOK, "产品数据获取成功", gin.H{
    "list": respProducts,
    "total": total,
  })
}

func GetProductByCat(c *gin.Context) {
	db := common.DB()

  // 获取请求参数
  id := c.Query("cat")

  // 查询对应数据
	var products []model.Product
	if err := db.Where("category_id = ?", id).Limit(6).Order("created_at desc").Find(&products).Error; err != nil {
		common.JSON(c, http.StatusInternalServerError, "分类数据获取失败", nil)
		return
	}

  // 封装去除不必要数据
  var catProducts []dto.ProductDto
  for _, v := range products {
    catProducts = append(catProducts, dto.ToProductDto(v))
  }
	common.JSON(c, http.StatusOK, "分类数据获取成功", catProducts)
}
